// 云函数入口文件
const db = uniCloud.database();

exports.main = async (event, context) => {
	const {
		id,
		quantity,
		type,
		order_id,
		sale_price
	} = event; // 从客户端传递的参数，id: 商品的id，quantity: 要增加的库存数量

	if (!id || typeof quantity !== 'number') {
		return {
			code: 400,
			msg: '缺少参数或参数错误'
		};
	}

	try {
		// 检查 type 是否有效
		if (type !== 1 && type !== 2) {
			return {
				code: 400,
				msg: '无效的操作类型'
			};
		}

		let number = 0;
		let sale_number = 0
		let sale_prices = 0
		if (type == 1) {
			number = -quantity
			sale_number = quantity
			sale_prices = sale_price
		} else {
			number = quantity
			sale_number = -quantity
			sale_prices = -sale_price
		}

		const updateRes = await db.collection('opendb-mall-goods').doc(id).update({
			remain_count: db.command.inc(number),
			yqx_count: db.command.inc(number),
			sale_num: db.command.inc(sale_number),
			sale_price: db.command.inc(sale_prices)
		});

		if (updateRes.updated === 1) {
			let notes = type == 1 ? '减少库存' : '增加库存';
			let inset = {
				order_id,
				huoping_id: id,
				notes: notes,
				quantity_changed: number,
				modified_at: new Date()
			};
			// 插入订单记录
			await db.collection('order-record').add(inset);

			return {
				code: 200,
				msg: '库存更新成功'
			};
		} else {
			return {
				code: 404,
				msg: '商品未找到'
			};
		}
	} catch (error) {
		return {
			code: 500,
			msg: '服务器错误',
			error: error?.message || '未知错误'
		};
	}
};